<script setup lang="ts">
import { postMealAPI, putMealAPI } from '@/services/goods'
import { useMemberStore } from '@/stores'
import { getMealListByIDAPI } from '@/services/goods'
import { onLoad } from '@dcloudio/uni-app'
import {
  selectMealAddressAPI
} from '@/services/address'
import { ref } from 'vue'
import type { FileData } from '@/types/goods'
import { postPictureAPI } from '@/services/goods'
import type { SelectMealItem } from '@/types/address'
import { useAddressStore } from '@/stores'
// 获取配送中心Store
const AddressStore = useAddressStore()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 获取配送中心列表数据
const addressList = AddressStore.addressList

// 表单数据
const form = ref({
  id: '',
  name: '',
  mealdesc: '',
  price: '',
  picture: '',
  taste: '',
  mealtype: '',
  mealdate: '',
  shopid: '',
  shopname: '',
})

// 获取页面参数
const query = defineProps<{
  id?: string
}>()

// 获取收货地址详情数据
const getMealListByIdDate = async () => {
  if (query.id) {
    // 发送请求
    const res = await getMealListByIDAPI(query.id)
    // 把数据合并到表单中
    Object.assign(form.value, res.result[0])
  }
  console.log(form.value.shopid, '0000000')
}


onLoad(() => {
  getMealListByIdDate()
  console.log(addressList)
})
// 动态设置标题
uni.setNavigationBarTitle({ title: query.id ? '修改套餐' : '新增套餐' })

const memberStore = useMemberStore()
//上传图片相关
const queryActivities = async (data: FileData) => {
  const res = await postPictureAPI(data)
  form.value.picture = res.result as string
}
//上传图片
const uploadImg = () => {
  //获取图片的临时路径
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择 拍照
    success: function (res) {
      //console.log('22222222222222222222222222')
      //console.log(((res.tempFiles as any)[0].path.split("."))[1], '1111');
      let tempFilePaths = res.tempFilePaths;
      let avatarUrlBase64 = '';
      if ((res.tempFiles as any)[0].size > 10 * 1024 * 1024) {
        uni.showToast({ title: '图片大小超过10M，请重新选择照片' });
        return;
      }
      const filedata = ref({
        path: '',
        avatarUrlBase64: ''
      })
      // 将图片转成base64格式
      uni.getFileSystemManager().readFile({
        filePath: tempFilePaths[0],
        encoding: 'base64',
        success(val) {
          console.log(tempFilePaths, '222222222222')
          filedata.value.path = ((tempFilePaths as any)[0].split("."))[1]
          filedata.value.avatarUrlBase64 = '' + val.data;
          //console.log(avatarUrlBase64)
          queryActivities(filedata.value);
        }
      });

    }
  });
}

// 修改类别
const onMealTypeChange: UniHelper.RadioGroupOnChange = (ev) => {
  form.value.mealtype = ev.detail.value
}

// 修改日期
const onMealDataChange: UniHelper.DatePickerOnChange = (ev) => {
  form.value.mealdate = ev.detail.value
}


// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  name: {
    rules: [{ required: true, errorMessage: '请输入名称' }],
  },
  mealdesc: {
    rules: [{ required: true, errorMessage: '请输入配菜' }],
  },
  taste: {
    rules: [{ required: true, errorMessage: '请输入口味' }],
  },
  mealdate: {
    rules: [{ required: true, errorMessage: '请选择日期' }],
  },
  price: {
    rules: [{ required: true, errorMessage: '请输入价格' }],
  },
  mealtype: {
    rules: [{ required: true, errorMessage: '请选择类型' }],
  },
  shopid: {
    rules: [{ required: true, errorMessage: '请选择门店' }],
  },
}

// 表单组件实例
const formRef = ref<UniHelper.UniFormsInstance>()


// 提交表单
const onSubmit = async () => {
  try {
    // 表单校验
    await formRef.value?.validate?.()
    // 校验通过后再发送请求
    if (query.id) {
      form.value.id = query.id
      // 修改地址请求
      await putMealAPI(form.value as any)
    } else {
      // 新建地址请求
      await postMealAPI(form.value as any)
    }
    // 成功提示
    uni.showToast({ icon: 'success', title: query.id ? '修改成功' : '添加成功' })
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 400)
  } catch (error) {
    uni.showToast({ icon: 'error', title: '请填写完整信息' })
  }
}
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view @tap="uploadImg" class="avatar-content">
        <image class="image" :src="form?.picture" mode="aspectFill" />
        <text class="text">{{ query.id ? '点击修改主图' : '点击创建主图' }}</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="content">
      <!-- 表单内容 -->
      <uni-forms :rules="rules" :model="form" ref="formRef">
        <uni-forms-item name="name" class="form-item">
          <text class="label">套餐名称</text>
          <input class="input" type="text" placeholder="请填写套餐名称" v-model="form!.name" />
        </uni-forms-item>
        <uni-forms-item name="mealdesc" class="form-item">
          <text class="label">套餐配菜</text>
          <input class="input" type="text" placeholder="请填写套餐配菜" v-model="form!.mealdesc" />
        </uni-forms-item>
        <uni-forms-item name="taste" class="form-item">
          <text class="label">套餐口味</text>
          <input class="input" type="text" placeholder="请填写套餐口味" v-model="form!.taste" />
        </uni-forms-item>
        <uni-forms-item name="mealdate" class="form-item">
          <text class="label">套餐日期</text>
          <picker @change="onMealDataChange" mode="date" class="picker" :value="form?.mealdate" start="1900-01-01"
            :end="new Date()">
            <view v-if="form?.mealdate">{{ form?.mealdate }}</view>
            <view class="placeholder" v-else>请选择套餐日期</view>
          </picker>
        </uni-forms-item>
        <uni-forms-item name="price" class="form-item">
          <text class="label">套餐价格</text>
          <input class="input" type="digit" step="0.01" placeholder="请填写套餐价格，保留两位小数" v-model="form!.price" />
        </uni-forms-item>
        <uni-forms-item name="mealtype" class="form-item">
          <text class="label">套餐类别</text>
          <radio-group @change="onMealTypeChange">
            <label class="radio">
              <radio value="早餐" color="#27ba9b" :checked="form?.mealtype === '早餐'" />
              早餐
            </label>
            <label class="radio">
              <radio value="午餐" color="#27ba9b" :checked="form?.mealtype === '午餐'" />
              午餐
            </label>
            <label class="radio">
              <radio value="晚餐" color="#27ba9b" :checked="form?.mealtype === '晚餐'" />
              晚餐
            </label>
          </radio-group>
        </uni-forms-item>
        <uni-forms-item name="shopid" class="form-item">
          <text class="label">出餐门店</text>
          <input v-if="query.id" disabled="disabled" class="input" v-model="form.shopname" />
          <uni-data-select v-else class="picker" v-model="form.shopid" :localdata="addressList"
            label="门店选择">请选择门店</uni-data-select>
        </uni-forms-item>
      </uni-forms>
      <!-- 提交按钮 -->
      <button @tap="onSubmit" class="form-button">保 存</button>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    // 调整 uni-forms 样式
    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 320rpx;
    height: 180rpx;
    border-radius: 5px;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>
